<template>
  <div>
    <el-row type="flex" justify="center">
      <el-col :span="12">
          <video autoplay ref="video"></video>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="6">
          <el-button type="primary" @click="train">训练</el-button>
          <el-button type="primary" @click="distinguish">识别</el-button>
      </el-col>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="12">
          <canvas hidden ref="canvas" width="400" height="400"></canvas>
      </el-col>
    </el-row>
  </div>

</template>

<script>
import axios from "axios";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Portrait",
  mounted() {
    this._initVueApp()
  },
  data(){
    return{
      images:[]
    }
  },
  methods:{
    //获取媒体设备
    async _initVueApp(){
      //获取摄像头
      this.$refs.video.srcObject = await navigator.mediaDevices.getUserMedia({video:true,audio:false});

      this.context = this.$refs.canvas.getContext("2d");
    },
    /**
     * 训练方法
     */
    train(){
      for(var i = 0;i<100;i++){
        this.context.drawImage(this.$refs.video,0,0,400,300);
        this.images.push(this.$refs.canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/,""))
      }
      console.log(this.images)
      //将图片传给后端
      axios.post('http://localhost:8080/Vue_test/train',{
          images:this.images
      })
          .then((resp)=>{
            this.images = [];
            console.log(resp)
            this.$message({
              message:'录入成功',
              type:'success'
            })
            this.$router.push("/")
          })
          .catch((error)=>{

            this.images = [];
            this.$message({
              message:'录入失败',
              type:'info'
            })
            console.log(error)
          })
    },

    distinguish(){
      this.context.drawImage(this.$refs.video,0,0,400,300);
      //将图片传给后端
      axios.post('http://localhost:8080/Vue_test/distinguish',{
        image:this.$refs.canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/,"")
      })
          .then((resp)=>{
            console.log(resp)
          })
          .catch((error)=>{
            console.log(error)
          })
    }
  }
}
</script>

<style scoped>
  video{
    width: 400px;
    height: 400px;
    margin-left:200px ;
  }
  canvas{
    width: 400px;
    height: 400px;
    margin-left:200px ;
  }

</style>